package com.leyou.cart.interceptor;

import com.leyou.common.auth.JwtUtils;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.utils.CookieUtils;
import com.leyou.common.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xiuer
 * @description 获取用户信息拦截器
 * @create 2019/7/12 11:22
 */
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            //获取用户的token
            String token = CookieUtils.getCookieValue(request, "leyou_Token");
            //解析token

            UserInfo user = JwtUtils.getInfoFromToken(token, UserInfo.class).getUserInfo();
            /*将用户信息放入容器中*/
            UserHolder.setUser(user);
            return true;
        } catch (Exception e) {
            log.error("【购物车微服务】解析用户异常 原因 {}", e.getMessage());
            throw new RuntimeException("token解析异常", e);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
